//
//  LoginFindSecretController.m
//  HaiGeEr_Student
//
//  Created by liuchen on 2018/9/10.
//  Copyright © 2018年 海格尔. All rights reserved.
//

//static修饰全局计时值
static int timeValue = 60;
#import "LoginFindSecretController.h"
#import "LoginResetSecretController.h"
#import "LoginBySecretController.h"
#import "LoginFindSecretView.h"
#import "UserModel.h"

@interface LoginFindSecretController ()
@property (nonatomic,strong) NSTimer *timer;
@property (nonatomic,weak) UIButton *backBtn;
@property (nonatomic,weak) UIButton *sureBtn;
@property (nonatomic,weak) LoginFindSecretView *loginFindSecretView;
@end

@implementation LoginFindSecretController

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setHidden:NO];
    if (nil != _timer) {
        [_timer invalidate];
        _timer = nil;
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setHidden:YES];
    [[CoachTabBarController shareLZHTabbarController].tabBar setHidden:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createSubView];
}

#pragma mark ==========创建视图==========
- (void)createSubView{
    self.view.backgroundColor = [UIColor whiteColor];
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, SYSTEM_STATUSBAR_HEGHT, 83*SCALEUNIT, 83*SCALEUNIT);
    [backBtn setImage:[UIImage imageNamed:@"8-4-1"] forState:UIControlStateNormal];
    [backBtn setImageEdgeInsets:UIEdgeInsetsMake(30*SCALEUNIT, 35*SCALEUNIT, 30*SCALEUNIT, 35*SCALEUNIT)];
    [backBtn addTarget:self action:@selector(backChange:) forControlEvents:UIControlEventTouchUpInside];
    _backBtn = backBtn;
    [self.view addSubview:self.backBtn];
    
    LoginFindSecretView *loginFindSecretView = [[LoginFindSecretView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.backBtn.frame), [UIScreen mainScreen].bounds.size.width, 535*SCALEUNIT)];
    [loginFindSecretView.codeBtn addTarget:self action:@selector(codeChange:) forControlEvents:UIControlEventTouchUpInside];
    _loginFindSecretView = loginFindSecretView;
    [self.view addSubview:self.loginFindSecretView];
    
    UIButton *sureBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    sureBtn.frame = CGRectMake(70*SCALEUNIT, CGRectGetMaxY(self.loginFindSecretView.frame)+85*SCALEUNIT, 610*SCALEUNIT, 90*SCALEUNIT);
    [sureBtn setTitle:@"确认" forState:UIControlStateNormal];
    [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sureBtn.titleLabel setFont:[UIFont systemFontOfSize:LoginFont]];
    [sureBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
    [sureBtn setBackgroundColor:LOGINBUTTONBACKRGBA];
    [sureBtn.layer setShadowColor:[UIColor blackColor].CGColor];
    [sureBtn.layer setShadowOffset:CGSizeMake(5*SCALEUNIT, 5*SCALEUNIT)];
    [sureBtn.layer setShadowOpacity:0.8];
    [sureBtn addTarget:self action:@selector(sureChange:) forControlEvents:UIControlEventTouchUpInside];
    _sureBtn = sureBtn;
    [self.view addSubview:self.sureBtn];
}

#pragma mark ==========发送验证码==========
- (void)codeChange:(UIButton *)btn{
    if (isEmpty(self.loginFindSecretView.phoneView.textField.text)) {
        [self showMessage:@"手机号不能为空"];
    } else if (!LOGINPHONECHECK(self.loginFindSecretView.phoneView.textField.text)){
        [self showMessage:@"手机号格式错误"];
    }else {
        [self showLoading];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
                             self.loginFindSecretView.phoneView.textField.text, @"phone", nil];
        [[NetworkEngine sharedClient] GET:LOGINSENDCODE data:dic success:^(id responseObject) {
            [self showSuccess:[responseObject objectForKey:@"msg"]];
            if ([[responseObject objectForKey:@"code"] integerValue] == 1) {
                //开启计时器
                self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(dealYzmBut) userInfo:nil repeats:YES];
            } else {[self showMessage:[responseObject objectForKey:@"msg"]];}
        } failure:^(NSString *error) {
            [self hideHUD];
        }];
    }
}

#pragma mark ==========定时器方法==========
- (void)dealYzmBut{
    
    UIButton *sender = self.loginFindSecretView.codeBtn;
    if (timeValue == 0) {
        [sender setTitle:@"重新发送" forState:UIControlStateNormal];
        sender.userInteractionEnabled = YES;
        timeValue = 60;
        [self.timer invalidate];
        return;
    }
    
    sender.userInteractionEnabled = NO;
    [sender setTitle:[NSString stringWithFormat:@"%d",timeValue] forState:UIControlStateNormal];
    timeValue--;
}

#pragma mark ==========确认按钮:执行登录操作==========
- (void)sureChange:(UIButton *)btn{
    if (isEmpty(self.loginFindSecretView.phoneView.textField.text)) {
        [self showMessage:@"请输入手机号"];
    }else if (isEmpty(self.loginFindSecretView.codeView.textField.text)) {
        [self showMessage:@"请输入验证码"];
    }else if (isEmpty(self.loginFindSecretView.codeView.textField.text)) {
        [self showMessage:@"请输入您设置的密码"];
    }else if (!LOGINPHONECHECK(self.loginFindSecretView.phoneView.textField.text)) {
        [self showMessage:@"手机号格式错误"];
    }else if ([self.loginFindSecretView.inputHideView.textField.text length]<6 || [self.loginFindSecretView.inputHideView.textField.text length]>20) {
        [self showMessage:@"密码格式错误"];
    }else {
        [self showLoading];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
                             self.loginFindSecretView.phoneView.textField.text, @"phone",
                             self.loginFindSecretView.codeView.textField.text, @"code",
                             BASE64(self.loginFindSecretView.inputHideView.textField.text), @"password", nil];
        [[NetworkEngine sharedClient] GET:LOGINFINDSECRET data:dic success:^(id responseObject) {
            [self showSuccess:[responseObject objectForKey:@"msg"]];
            if ([[responseObject objectForKey:@"code"] integerValue] == 1) {
                [self performSelector:@selector(loginIn) withObject:nil afterDelay:1.5f];
            } else {[self showMessage:[responseObject objectForKey:@"msg"]];}
        } failure:^(NSString *error) {
            [self hideHUD];
        }];
    }
}

#pragma mark ==========登录==========
- (void)loginIn{
    if (self.jumpNum == 1) {
        [[[UIApplication sharedApplication].delegate window].rootViewController removeFromParentViewController];
        [[UIApplication sharedApplication].delegate window].rootViewController = [[UINavigationController alloc] initWithRootViewController:[[LoginBySecretController alloc] init]];
        [[[UIApplication sharedApplication].delegate window] makeKeyAndVisible];
    }else {
        [self.navigationController popViewControllerAnimated:YES];
    }
//    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
//                         self.loginFindSecretView.phoneView.textField, @"phone",
//                         self.loginFindSecretView.codeView.textField, @"code",
//                         @"2", @"loginType", nil];
//    [[NetworkEngine sharedClient] GET:LGGINBYPASSWORD data:dic success:^(id responseObject) {
//        [self showOnlyTextDialog:[responseObject objectForKey:@"msg"]];
//        if ([[responseObject objectForKey:@"code"] integerValue] == 1) {
//            [UserMessage sharedInstance].model = [UserModel mj_objectWithKeyValues:[responseObject objectForKey:@"data"]];
//            [[NSUserDefaults standardUserDefaults] setObject:[responseObject objectForKey:@"data"] forKey:@"userMessage"];
//            [[NSUserDefaults standardUserDefaults] synchronize];
//            [self performSelector:@selector(jumpToMainPage) withObject:nil afterDelay:1.5f];
//        }
//    } failure:^(NSString *error) {
//    }];
}
- (void)jumpToMainPage{
    if ([[UserMessage sharedInstance].model.loginTime length]==0) {
        [self.navigationController pushViewController:[[LoginResetSecretController alloc] init] animated:YES];
    }else {
        [UIApplication sharedApplication].keyWindow.rootViewController= [CoachTabBarController shareLZHTabbarController];
    }
}

#pragma mark ==========返回上一层==========
- (void)backChange:(UIButton *)btn{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
